/*================ App Table 3: Synthetic Control Weights ===================*/

foreach loop of numlist 3 {

global lag = 1
global lead = `loop'

foreach cutoff of numlist 0.10 /*0.25*/ 0.5 0.75 1 {

	global cutoff = `cutoff'
	use "${data1}state_panel_mw_poverty_84_w", clear

	//Merge in Controls (EITC and stuff)
	preserve
	use "${data2}aca_expansion_eitc.dta", clear
	replace year = year+1 //Match policy at t-1 to t
	tempfile controls
	save `controls'
	restore
	merge 1:1 state_fips year using `controls', keep(1 3) nogen

	sort state_fips year
	by state_fips: gen mw_change_nom = mw - mw[_n-1]
	replace mw_change_nom=0 if mw_change_nom==.

	*gen tryear=year if mw_change>=$cutoff
	gen tryear=year if mw_change_nom>=$cutoff

	//Ignore "treatment" if "treatment" occured the year before
	sort state_fips year
	by state_fips: gen tryear_lag=tryear[_n-1]
	gen tryear_eff = tryear
	replace tryear_eff=. if tryear-tryear_lag==1
	drop tryear_lag

	sort tryear_eff state_fips 
	gen eventid=_n if tryear_eff!=.

	qui sum eventid 
	local max = r(max)

	//Delete all files
	local datafiles: dir "${synth}" files "weight*.dta"
	foreach datafile of local datafiles {
		erase "${synth}`datafile'"
	}
	
	local datafiles: dir "${synth}" files "synth*.dta"
	foreach datafile of local datafiles {
		erase "${synth}`datafile'"
	}

	if "$placebo"=="yes" {
		local datafiles: dir "${synth}" files "coef*.dta"
		foreach datafile of local datafiles {
			erase "${synth}`datafile'"
		}
	}
	
	local countevent = 0
	foreach i of numlist 1/`max' {
		preserve
		
		timer clear
		timer on 1
		
		dis `i' 
		qui {
			** Figure out Treatment State + Year
			sum tryear if eventid==`i'
			global tryear = r(mean)
			
			sum state_fips if eventid==`i'
			global trfips = r(mean)
			

			***Sample Cuts
			
			//Keep states w/o "treatment" (> -25cent min wage increase) 3 years before & 1 year after
			local lead = $lead
			local lag = $lag
			keep if inrange(year, $tryear -`lead', $tryear + `lag') 
			if `cutoff'<=0.25 {
				drop if mw_change_nom >=`cutoff' & state_fips!=$trfips
			} 
			if `cutoff'<=0.5 & `cutoff'>0.25 {
				drop if mw_change_nom >=0.25 & state_fips!=$trfips
			} 
			else {
				drop if mw_change_nom >=0.5 & state_fips!=$trfips
			}
			
			
			//Keep "treatment" states only if NO pre-treat min wage increase
			drop if inrange(tryear, $tryear -`lead', $tryear - 1)  & state_fips==$trfips
			bys state_fips: gen count=_N
			if `lag'==1 {
				keep if (count==`lead'+`lag'+1) | (count==`lead'+1 & ${tryear}==2020)   //Make sure to change this when cutoff changes!!
			}
			
			if `lag'==2 {
				keep if (count==`lead'+`lag'+1) | (count==`lead'+1 & ${tryear}==2020) |  (count==`lead'+2 & ${tryear}==2019)   //Make sure to change this when cutoff changes!!
			}
			
			//Ignore cases where there are NO treatment state
			sum state_fips if state_fips==$trfips
			local obs =r(N)
			
			if `obs' > 0 {
				//Ignore cases where there are NO donor states w/in the same division
				qui sum division if eventid==`i'
				local trdiv = r(mean)
				bys state_fips: gen stateid=1 if _n==1 & division==`trdiv'
				egen count_div= count(stateid)
				sum count_div
				local count_div = r(mean)
						
				//Ignore cases where there are only ONE donor state
				drop stateid
				bys state_fips: gen stateid=1 if _n==1 
				egen count_donor= count(stateid)
				sum count_donor
				local count_donor = r(mean) 	
			
				**Create Pre-Treat Mean
				gen preoutcome = under_100 if year<$tryear 
				bys state_fips: egen pretreatmean = mean(preoutcome)

				
				***Run Synthetic Control
				if `count_div' > 1 & `count_donor' > 3  {						
					xtset state_fips year
					local pre=$tryear-`lead'
					local before=$tryear-1
					local post=$tryear+`lag'
					if `post'>2020 { 
						local post=$tryear
					}
					
					
					local control1=""
					foreach t of numlist `pre'/`before' {
						local control1 = "`control1'" + "under_100(`t') "
					}
					
					local control2 = "pretreatmean "
					foreach var of varlist hpi ur_high_edu wage_high_edu {	
						foreach t of numlist `pre' $tryear `post' {
							local control2 = "`control2'" + "`var'(`t') "
						}
					}
					
					local control3 = "pretreatmean "
					foreach var of varlist ur gdppc {	
						foreach t of numlist `pre' $tryear `post' {
							local control3 = "`control3'" + "`var'(`t') "
						}
					}
					
					
					local control4 = "`control2'"
					foreach var of varlist eitc tanf4 {	
						foreach t of numlist `pre' $tryear `post' {
							local control4 = "`control4'" + "`var'(`t') "
						}
					}	
					dis "`control1'"
					dis "`control2'"
					dis "`control3'"
					dis "`control4'"
					
					tempfile save1
					synth under_100	`control1', trunit($trfips) trperiod($tryear) keep(`save1')
					if "$placebo" == "yes" runplacebo "`control1'" `i' 1

					tempfile save2
					synth under_100	`control2', trunit($trfips) trperiod($tryear) keep(`save2')
					if "$placebo" == "yes" runplacebo "`control2'" `i' 2

					tempfile save3
					synth under_100 `control3', trunit($trfips) trperiod($tryear) keep(`save3')
					if "$placebo" == "yes" runplacebo "`control3'" `i' 3
					
					tempfile save4
					synth under_100 `control4', trunit($trfips) trperiod($tryear) keep(`save4')
					if "$placebo" == "yes" runplacebo "`control3'" `i' 4
					
					
					gen treated = state_fips == $trfips & year >= $tryear
					qui sdid under_100 state_fips year treated, vce(noinference)
					matrix weight = e(omega)
					svmat weight
					keep if weight2!=.
					keep weight1 weight2
					ren (weight1 weight2) (_W_Weight _Co_Number )
					gen id = `i'
					gen treat_division = `trdiv'
					gen treat_year = $tryear
					gen treat_fips=$trfips
					gen no_donor = `count_donor' - 1
					gen no_donor_div = `count_div' -1
					save "${synth}weight5_`i'.dta", replace


					foreach j of numlist 1/4 {
						use `save`j'', clear
						gen id = `i'
						gen treat_division = `trdiv'
						gen treat_year = $tryear
						gen treat_fips=$trfips
						gen no_donor = `count_donor' - 1
						gen no_donor_div = `count_div' -1
						save "${synth}weight`j'_`i'.dta", replace
						
						use `save`j'', clear
						keep _Y_treated _Y_synthetic _time
						keep if  _time!=.
						gen treat_year = $tryear
						gen treat_fips=$trfips
						gen model_no=`j'
						save "${synth}synth`j'_`i'.dta", replace
						
						/*keep if  _time >= $tryear 
						gen att = _Y_treated - _Y_synthetic
						collapse (mean) att, by(treat_*)
						gen model_no = `j'
						save "${synth}coef`j'_`i'.dta", replace*/

					}
					
					local countevent = `countevent' + 1
				}
			}
		}		
		
		restore
	}
	
	timer off 1
	timer list


	//Create Total Weights Table
	**Census Division
	use "${data2}state_geocodes.dta", clear
	keep state_fips division
	ren state_fips donor_fips
	ren division donor_div
	tempfile census_div
	save `census_div'


	**Read in Synth Weights
	foreach i of numlist 1/5 {
		local datafiles: dir "${synth}" files "weight`i'*.dta"
		clear
		foreach datafile of local datafiles {
			qui append using "${synth}`datafile'"
		}

		//Merge in Division 
		ren _Co_Number donor_fips
		merge m:1 donor_fips using `census_div'
		drop if _merge==2

		keep if donor_div==treat_division
		
		preserve
		collapse (sum) _W_Weight (mean) no_donor* , by(treat_fips treat_year treat_division)
		*preserve
		*collapse (sum) _W_Weight, by(treat_fips treat_year)
		drop treat_division no_donor*
		ren _W_Weight weights
		ren treat_fips unit
		ren treat_year tryear
		gen model_no = `i'
		tempfile wt`i' 
		save `wt`i''
		restore
		
		ren _W_Weight weights`i'
		collapse (mean) weights* no_donor*, by(treat_division) 
		tempfile col`i'
		save `col`i''		
		
	}

	**Merge in Synth Weights
	use `col1', clear
	merge 1:1 treat_division using `col2', nogen
	merge 1:1 treat_division using `col3', nogen
	merge 1:1 treat_division using `col4', nogen
	merge 1:1 treat_division using `col5', nogen


	gen div = ""
	replace div = "New England" if treat_division==1
	replace div = "Middle Atlantic" if treat_division==2
	replace div = "East North Central" if treat_division==3
	replace div = "West North Central" if treat_division==4
	replace div = "South Atlantic" if treat_division==5
	replace div = "East South Central" if treat_division==6
	replace div = "West South Central" if treat_division==7
	replace div = "Mountain" if treat_division==8
	replace div = "Pacific" if treat_division==9

	keep div weights* no_donor*
	order div weights* no_donor*
	
	sort div
	
	gen no_event = `countevent'

	local save = $cutoff*100
	export delimited using "${tab}synth_donors_`save'_${lead}_${lag}", replace
	

}
}
